define([
    'dojo/_base/declare',
    'geomap/plugins/layers/CanvasLayer',
    'dojo/dom-construct',
    'esri/geometry/Point',
    'dojo/_base/config',
    'dojo/on',
], function (declare, CanvasLayer, domConstruct, Point, config, on) {
    return declare([CanvasLayer], {
        _refresh: function () {
            if (!this.visible) {
                return;
            }
            if (this.canvas && this.mapv) {
                if (this.map) {
                    this.setScale(this.map, this.canvas);
                }
                if (!this._elementVisible) {
                    return;
                }
                this.canvas.width = this.map.width;
                this.canvas.height = this.map.height;
                this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
                this.canvasResolutionScale(this.ctx);

                var map_data = [];
                var item = null;
                for (var i = 0, len = this.data.length; i < len; i++) {
                    item = this.data[i];
                    var point = new Point(item[this.lngFieldName], item[this.latFieldName]);
                    var p = this.map.toScreen(point);
                    map_data.push({
                        geometry: {
                            type: 'Point',
                            coordinates: [p.x, p.y],
                        },
                        count: this.data[i][this.countFieldName] || 1,
                    });
                }
                var DataSet = this.mapv.DataSet;
                this.dataSet = new DataSet(map_data);
                var options = {
                    size: this.options.size || 20,
                    gradient: this.gradient,
                    draw: 'heatmap',
                    max: this.calMaxCount(),
                    maxOpacity: this.maxOpacity,
                };
                this.canvasDrawHeatmap(this.ctx, this.dataSet, options);
            }
        },
        calMaxCount: function () {
            this.data.sort(function (obj1, obj2) {
                var val1 = obj1.count;
                var val2 = obj2.count;
                if (val1 < val2) {
                    return -1;
                } else if (val1 > val2) {
                    return 1;
                } else {
                    return 0;
                }
            });
            var max = this.data[this.data.length - 1][this.countFieldName];
            return max;
        },
        canvasDrawHeatmap(context, dataSet, options) {
            var strength = options.strength || 0.3;
            context.strokeStyle = 'rgba(0,0,0,' + strength + ')';

            options = options || {};

            var data = this.dataSet.get();

            context.save();

            this.drawGray(context, data, options);

            if (!options.absolute) {
                var colored = context.getImageData(
                    0,
                    0,
                    context.canvas.width,
                    context.canvas.height
                );
                this.colorize(
                    colored.data,
                    this.getImageData({
                        defaultGradient: options.gradient || {
                            0.25: 'rgba(0, 0, 255, 1)',
                            0.55: 'rgba(0, 255, 0, 1)',
                            0.85: 'rgba(255, 255, 0, 1)',
                            1.0: 'rgba(255, 0, 0, 1)',
                        },
                    }),
                    options
                );

                context.putImageData(colored, 0, 0);

                context.restore();
            }
        },
        colorize(pixels, gradient, options) {
            var maxOpacity = options.maxOpacity || 0.8;

            for (var i = 3, len = pixels.length, j; i < len; i += 4) {
                j = pixels[i] * 4; // get gradient color from opacity value

                if (pixels[i] / 256 > maxOpacity) {
                    pixels[i] = 256 * maxOpacity;
                }

                pixels[i - 3] = gradient[j];
                pixels[i - 2] = gradient[j + 1];
                pixels[i - 1] = gradient[j + 2];
            }
        },
        getImageData: function getImageData(config) {
            var gradientConfig = config.gradient || config.defaultGradient;
            if (typeof document === 'undefined') {
                var Canvas = require('canvas');
                var paletteCanvas = new Canvas(256, 1);
            } else {
                var paletteCanvas = document.createElement('canvas');
            }
            var paletteCtx = paletteCanvas.getContext('2d');

            paletteCanvas.width = 256;
            paletteCanvas.height = 1;

            var gradient = paletteCtx.createLinearGradient(0, 0, 256, 1);
            for (var key in gradientConfig) {
                gradient.addColorStop(parseFloat(key), gradientConfig[key]);
            }

            paletteCtx.fillStyle = gradient;
            paletteCtx.fillRect(0, 0, 256, 1);

            return paletteCtx.getImageData(0, 0, 256, 1).data;
        },
        drawGray: function (context, dataSet, options) {
            var max = options.max || 100;

            var size = options._size;
            if (size == undefined) {
                size = options.size;
                if (size == undefined) {
                    size = 13;
                }
            }
            var Intensity = this.mapv.utilDataRangeIntensity;

            var color = new Intensity({
                gradient: options.gradient,
                max: max,
            });

            var circle = this._createCircle(size);

            var data = dataSet;

            var dataOrderByAlpha = {};

            data.forEach(function (item, index) {
                var count = item.count === undefined ? 1 : item.count;
                var alpha = Math.min(1, count / max).toFixed(2);
                dataOrderByAlpha[alpha] = dataOrderByAlpha[alpha] || [];
                dataOrderByAlpha[alpha].push(item);
            });

            for (var i in dataOrderByAlpha) {
                if (isNaN(i)) continue;
                var _data = dataOrderByAlpha[i];
                context.beginPath();
                if (!options.withoutAlpha) {
                    context.globalAlpha = i;
                }
                _data.forEach(function (item, index) {
                    if (!item.geometry) {
                        return;
                    }

                    var coordinates = item.geometry._coordinates || item.geometry.coordinates;
                    var type = item.geometry.type;
                    if (type === 'Point') {
                        var count = item.count === undefined ? 1 : item.count;
                        context.globalAlpha = count / max;
                        context.drawImage(
                            circle,
                            coordinates[0] - circle.width / 2,
                            coordinates[1] - circle.height / 2
                        );
                    } else if (type === 'LineString') {
                        pathSimple.draw(context, item, options);
                    } else if (type === 'Polygon') {
                    }
                });

                context.strokeStyle = color.getColor(i * max);
                context.stroke();
            }
        },
        _createCircle(size) {
            if (typeof document === 'undefined') {
                var Canvas = require('canvas');
                var circle = new Canvas();
            } else {
                var circle = document.createElement('canvas');
            }
            var context = circle.getContext('2d');
            var shadowBlur = size / 2;
            var r2 = size + shadowBlur;
            var offsetDistance = 10000;

            circle.width = circle.height = r2 * 2;

            context.shadowBlur = shadowBlur;
            context.shadowColor = 'black';
            context.shadowOffsetX = context.shadowOffsetY = offsetDistance;

            context.beginPath();
            context.arc(r2 - offsetDistance, r2 - offsetDistance, size, 0, Math.PI * 2, true);
            context.closePath();
            context.fill();
            return circle;
        },
    });
});
